//home模块的小仓库---四部分 state mutations actions getters
//state存储数据的地方
import { reqGetCode, reqLogin, reqUserInfo,reqLogOut} from "@/api";
import { GET_TOKEN, REMOVE_TOKEN, SET_TOKEN } from "@/utils/token";
const state = {
    code: '',
    //存储令牌
    token:GET_TOKEN(),//存储token
    nickName:''//用户名字
};
//mutations:唯一可以修改仓库数据的地方
const mutations = {
    GETCODE(state, code) {
        state.code = code;
    },
    SET_TOKEN(state,token){
        state.token =token
    },
    LOGOUT(state){
        state.token  = ''
        state.nickName =''
        REMOVE_TOKEN()//本地存储token清除
    },
    SET_NICKNAME(state,nickName){
        state.nickName = nickName;
    }

};
//actions:可以书写业务、逻辑
const actions = {
    //获取验证码
    async getCode({ state, commit, dispatch }, phone) {
        let result = await reqGetCode(phone);
        //实际开发,发完请求，就不管了！！！！
        if (result.code == 200) {
            commit('GETCODE', result.data);
            return 'ok'
        } else {
            return Promise.reject();
        }
    },
    // 用户登录
   async login({dispatch,state,commit},data){
        let result = await reqLogin(data)
        console.log(result)
        if(result.code==200){
            // 登录成功
            commit('SET_TOKEN',result.data.token)
            // 第一次遇到token：持久化存储token
            SET_TOKEN(result.data.token)
            return 'ok'

        }else{
            // 登录失败
            return Promise.reject(result.message)
        }
    },
   //退出登录
   async logout({commit,state,dispatch}){
    let result   = await reqLogOut(); 
    console.log(result)
    if(result.code==200){
        commit('LOGOUT');
        return 'ok';
    }else{
        return Promise.reject();
    }
  },
//   获取用户信息
async getUserInfo({state,commit,dispatch}) {
    let result = await reqUserInfo();
    console.log(result)
     if(result.code==200){
         //存储用户名字
         commit('SET_NICKNAME',result.data.nickName);
         return 'ok'
     }else{
         return Promise.reject();
     }
},

};
//计算属性getters
const getters = {};

//对外暴露小仓库
export default {
    namespaced: true,
    state,
    mutations,
    actions,
    getters
}
